package com.gin.kotlin.vegetables_kot.base

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build

/**
 * 通知推送工具类
 */
class NotificationUtils {

    companion object {
        /**
         * 获取管理器
         * @param context Context
         * @return [NotificationManager]
         */
        @JvmStatic
        fun getNotificationManager(context: Context): NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        /**
         * 获取通知通道
         * @param context Context
         * @param channelId 通道ID（自定义）
         * @return (NotificationChannel..NotificationChannel?)
         */
        @JvmStatic
        fun getChannel(context: Context, channelId: String, importance: Int = NotificationManager.IMPORTANCE_DEFAULT) = getNotificationManager(context)
            .let { it.getNotificationChannel(channelId) ?: (createChannel(context, channelId, importance)) }

        /**
         * 创建通知通道
         * @param context Context
         * @param channelId String
         * @param importance Int
         * @return NotificationChannel
         */
        @JvmStatic
        fun createChannel(context: Context, channelId: String, importance: Int = NotificationManager.IMPORTANCE_DEFAULT) = getNotificationManager(context).let {
            val channel = NotificationChannel(channelId, channelId, importance)
            it.createNotificationChannel(channel)
            channel
        }

        /**
         * 发布通知推送
         * @param context Context
         * @param id 推送id
         * @param notification 通知推送对象，通过 [Notification.Builder] 构建
         * @param tag tag
         * @return NotificationManager
         */
        @JvmStatic
        fun notify(context: Context, id: Int, notification: Notification, tag: String? = null) =
            getNotificationManager(context).also {
                cancel(context, id)
                it.notify(tag, id, notification)
            }

        /**
         * 关闭一个已存在的通知推送
         * @param context Context
         * @param id Int
         * @return NotificationManager
         */
        @JvmStatic
        fun cancel(context: Context, id: Int) = getNotificationManager(context).also { it.cancel(id) }

        /**
         * 构造一个打开活动的意图
         * @param context Context
         * @param cls 活动类对象
         * @param requestCode Int
         * @return PendingIntent
         */
        @JvmStatic
        fun buildPendingIntent(context: Context, cls: Class<*>, requestCode: Int = 0): PendingIntent = PendingIntent.getActivity(
            context,
            requestCode,
            Intent(context, cls),
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_IMMUTABLE else PendingIntent.FLAG_UPDATE_CURRENT
        )
    }
}